<script setup lang="ts">
import { onMounted, ref } from 'vue'
import { omit } from 'lodash-es'
import { roleConfig } from './config'
import { addRole, deleteRole, getRole, updateRole } from '@/api/role'
import PageFormTable from '@/components/page/BaseFormTable/index.vue'
import { getMenu } from '@/api/system'
import { getPermission } from '@/api/permission'
import { useFetch } from '@/composables/useFetch'
import { arrayToTree, getParentKeys } from '@/utils'

const PageFormTableRef = ref<InstanceType<typeof PageFormTable>>()

// 页面请求
const { data: menuResult, execute: getMenuListExecute } = useFetch((parmas: any) => getMenu(parmas))
const { data: permissionResult, execute: getPermissionListExecute } = useFetch((parmas: any) => getPermission(parmas))

const apiConfig = {
  getTableList: getRole,
  addTableItem: addRole,
  updateTableItem: updateRole,
  deleteTableItem: deleteRole,
  _handleModel,
  _handleEditModel,
}

const treeList = ref([])
function _handleModel(model: any) {
  // 解决选中了子菜单但是其父菜单没有选的情况(自动给其加上)
  const menuList = menuResult.value!.data
  const parentKeys = new Set()
  model.menu.forEach((menuItem: string) => {
    menuList.forEach((item: any) => {
      if (item.name === menuItem) {
        const nodes = getParentKeys(treeList.value, item.pid)
        nodes.forEach((node: any) => parentKeys.add(node.name))
      }
    })
  })
  model.menu = Array.from(new Set(model.menu.concat(Array.from(parentKeys))))
  return model
}

function _handleEditModel(data: any) {
  const editData = omit(data, ['createTime', 'updateTime'])
  return editData
}

const initRoleConfig = ref(roleConfig)
onMounted(() => {
  _handleInitRoleForm()
})

async function _handleInitRoleForm() {
  await getMenuList()
  await getPermissionList()
  treeList.value = arrayToTree(menuResult.value!.data, 0)

  const menuChildren = menuResult.value!.data.map((item: any) => {
    return {
      type: 'checkbox',
      label: item.name,
      value: item.name,
      disabled: item.active === 0,
    }
  })
  const permissionChildren = permissionResult.value!.data.map((item: any) => {
    return {
      type: 'checkbox',
      label: item.code,
      value: item.code,
    }
  })

  initRoleConfig.value.options = roleConfig.options.map((item: any) => {
    if (item.prop === 'menu') {
      return {
        ...item,
        children: menuChildren,
      }
    }
    if (item.prop === 'permissions') {
      return {
        ...item,
        children: permissionChildren,
      }
    }
    return item
  })
}

async function getMenuList(params?: any) {
  await getMenuListExecute(params)
}

async function getPermissionList(params?: any) {
  await getPermissionListExecute(params)
}
</script>

<template>
  <PageFormTable
    ref="PageFormTableRef"
    :config="initRoleConfig"
    :api-config="apiConfig"
  >
    <template #customs="{ column, record }">
      <template v-if="column.dataIndex === 'action'">
        <div class="gp__flex-start">
          <a-button class="gp__plain-btn" @click.stop="PageFormTableRef?.onClickEditForm({ ...record })">
            {{ roleConfig.text.editAction }}
          </a-button>
          <a-popconfirm
            title="Are you sure delete this role?"
            cancel-text="No"
          >
            <template #okButton>
              <a-button type="primary" size="small" :loading="PageFormTableRef?.deleteLoading" @click="PageFormTableRef?.onClickDeleteAction({ id: record.id })">
                Yes
              </a-button>
            </template>
            <a-button danger @click.stop>
              Delete
            </a-button>
          </a-popconfirm>
        </div>
      </template>
    </template>
  </PageFormTable>
</template>
